package org.teemor.demo.kafka.javaclient.producer;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/2/14
 */
public class SimpleProducer {

    public void simpleProdce() throws ExecutionException, InterruptedException {
        Properties props = new Properties();
        props.put("bootstrap.servers", "common.teemor.xyz:9092");
        props.put("acks", "all");
        props.put("retries", 3);
        props.put("batch.size", 16384);
        props.put("linger.ms", 1);
        props.put("buffer.memory", 33554432);
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("transactional.id", "123213");
        Producer<String, String> producer = new KafkaProducer<>(props);
        producer.initTransactions();
        producer.beginTransaction();
        for (int i = 0; i < 100; i++) {

            Future<RecordMetadata> future = producer.send(new ProducerRecord<String, String>("test", Integer.toString(i)), new Callback() {
                @Override
                public void onCompletion(RecordMetadata metadata, Exception exception) {
                    System.out.println("发送成功");
                }
            });
//            RecordMetadata o = future.get();
//            System.out.println(o.toString());

        }
//        producer.commitTransaction();
        producer.abortTransaction();
        producer.close();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        SimpleProducer simpleProducer = new SimpleProducer();
        simpleProducer.simpleProdce();
    }
}
